package middleware

import (
	"gin_mall/pkg/e"
	"gin_mall/pkg/utils"
	"gin_mall/serializer"
	"time"

	"github.com/gin-gonic/gin"
)

func JWT() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		code := e.Success
		token := ctx.GetHeader("authorization")
		var claims *utils.Claims = nil
		var err error = nil
		if token == "" {
			code = e.ErrorAuthTokenIsNull
		} else {
			claims, err = utils.ParseToken(token)
			if err != nil {
				code = e.ErrorAuthCheckTokenFailed
			} else if time.Now().Unix() > claims.ExpiresAt.Unix() {
				code = e.ErrorAuthCheckTokenExpire
			}
		}
		if code != e.Success {
			ctx.JSON(200, serializer.Response{
				Status: code,
				Msg:    e.GetMsg(code),
				Error:  err.Error(),
			})
			ctx.Abort()
			return
		}
		ctx.Set("token", *claims)
		ctx.Next()
	}
}
